<?php

namespace App\Service\Auth\v1_1_0;

use App\Constants\ErrorCode;
use App\Event\InviteEvent;
use App\Event\RegDoneEvent;
use App\Helpers\DateUtil;
use App\Model\Message;
use App\Model\NickNamePool;
use App\Model\User;
use App\Model\UserActLog;
use App\Model\UserProfile;
use App\Service\BaseService;
use Error;
use Psr\EventDispatcher\EventDispatcherInterface;

/**
 * 完善资料
 */
class FixMaleProfileService extends BaseService
{
    protected function RoVerifyList()
    {
        return [
            'birthday' => "|string",
            'gender' => "|int",
            'invite_code' => "|string"
        ];
    }

    public function handle()
    {
        $userId = $this->getUserId();
        $user = $this->getUser();
        $birthday = $this->request->input('birthday');
        $gender = $this->request->input('gender', -1);
        $inviteCode = $this->request->input('invite_code', '');
        $avatar = $this->request->input('avatar', '');
        $cid = $this->request->input('cid','');
        $info = ['user_id' => $userId];
        //绑定年龄
        if ($gender > -1) {
            $info['user_profile_id'] = UserProfile::makeProfileUid($userId);
            $info['gender'] = 1;
            $info['nick_name'] = NickNamePool::pickNickName(1);
            $info['avatar'] = $avatar ?: UserProfile::pickAvatar(1);
            //更新融云信息
            $result = User::updateIMInfo($user->im_account, $info['nick_name'], $info['avatar']);
        }

        
        if(!empty($avatar)){
            $avatarStatus = UserActLog::FLAG_OK;
            UserActLog::addRecord($userId, UserActLog::ACT_AVATAR, $avatar, $avatarStatus);
        }

        //绑定生日
        if ($birthday) {
            if (DateUtil::dateDiff($birthday, date('Y-m-d'), 'Y') < 18) {
                return $this->setError(ErrorCode::PARAMETER_ERROR, '暂不开放该年龄用户注册～');
            }
            $info['birthday'] = $birthday;
        }

        //绑定邀请码
        if ($inviteCode && UserProfile::isProfileIdValid($inviteCode)) {
            if(empty(User::checkByTimeInvite($cid))){
                $profile = UserProfile::getInfoByProfileId($inviteCode);
                $info['invite_code'] = $inviteCode;
                make(EventDispatcherInterface::class)->dispatch(new InviteEvent($profile->user_id, $userId, $profile));
            }else{
                Message::sendXiaomishuCustomMsg($userId, '您好，邀请好友同一设备在30天内只能被邀请一次，您的设备此前已经被邀请过，此次的邀请码视为无效邀请。如有疑问，请联系在线客服。','填写邀请码超限通知');
            }

        }
        //添加或更新用户信息
        if (count($info) == 1) return ['result' => 0];
        $result = UserProfile::updateOrCreate(['user_id' => $userId], $info);

        $ret['result'] = $result ? 1 : 0;
        $ret['user_info'] = $this->packBaseUserInfo($user);

        //注册完成事件
        make(EventDispatcherInterface::class)->dispatch(new RegDoneEvent($userId, $gender));
        return $ret;
    }
}
